package com.nny.alarm.alert;

import java.util.Calendar;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.text.format.DateFormat;
import android.view.MotionEvent;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.nny.alarm.R;
import com.nny.alarm.more.AlarmBriefUtil;
import com.umeng.analytics.MobclickAgent;
import com.uxwine.alarm.Alarm;
import com.uxwine.alarm.AlarmCalc;
import com.uxwine.alarm.AlarmCore;
import com.uxwine.alarm.AlarmDao;
import com.uxwine.alarm.Cmd;
import com.uxwine.alarm.Settings;
import com.uxwine.alarm.Snooze;
import com.uxwine.cmm.BaseFragmentActivity;
import com.uxwine.util.Log;
import com.uxwine.util.UxToast;
import com.uxwine.widget.DoubleClick;

public class AlertActivity extends BaseFragmentActivity implements OnActionListener
{
	AlarmBriefUtil mAUtil;
	DoubleClick mDoubleClick;
	NNYFragment mFragment;
	
	Alarm mAlarm;
	Snooze mSnooze;
	NNYGesture mGestrue;
	long mTriggerTime;
	MReceiver mReceiver;
	
	static final String SCREEN_OFF = "screen_off";

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		if(load(getIntent()))
		{
            Log.d("new-zzm", "AlertActivity onCreate...");
			requestFullScreen();
			setupView();
			registerReceiver();
			return;
		}		
        Log.d("new-zzm", "AlertActivity no alert data");
		dismiss();
	}
	
	@Override
	public void onResume() 
	{
		super.onResume();
		// If the alarm was deleted at some point, disable snooze.
		if (AlarmDao.getAlarm(getContentResolver(), mAlarm.id) == null)
		{
			
		}
	}
	
	@Override
    public void onBackPressed()
	{
        return;
    }
	
	
	
	@Override
	public boolean dispatchTouchEvent(MotionEvent ev)
	{
		if(mGestrue.onTouchEvent(ev))
			return true;
		return super.dispatchTouchEvent(ev);
	}

	@Override
	protected void onDestroy()
	{
		if(null != mReceiver)
			unregisterReceiver(mReceiver);
		super.onDestroy();
	}

	@Override
	public boolean onAction(int type)
	{
		if(type == OnActionListener.ACTION_DISMISS)
		{
			dismiss();
		}
		else if(type == OnActionListener.ACTION_SNOOZE)
		{
			snooze();
		}
		return false;
	}
	
	protected void setupView()
	{
		setContentView(R.layout.activity_alert);		
		FragmentManager fm = getSupportFragmentManager();
		mFragment = (NNYFragment)fm.findFragmentById(R.id.alert_frg_action);
		mFragment.setOnActionListener(this);
		

		mSnooze = Snooze.getInstance(this);
		mDoubleClick = new DoubleClick();		
		mAUtil = AlarmBriefUtil.getInstance(this);
		
		TextView tvTime = (TextView)findViewById(R.id.alert_tv_time);
		TextView tvCycle = (TextView)findViewById(R.id.alert_tv_cycle);
		TextView tvBrief = (TextView)findViewById(R.id.alert_tv_brief);
		
		final Alarm alarm = mAlarm;
		tvBrief.setText(alarm.label);		
		Calendar trigger = AlarmCalc.triggerTime(alarm.time, alarm.cycle);
		if(alarm.cycle.isOnce())
		{
			trigger.setTimeInMillis(alarm.trigger);
		}
		tvTime.setText(mAUtil.getBaseTimeString(alarm, trigger));
		tvCycle.setText(mAUtil.getCycleString(alarm));

		mGestrue = new NNYGesture(this);
		mGestrue.setOnActionListener(this);
	}
	
	protected boolean load(Intent intent)
	{
		mAlarm = intent.getParcelableExtra(Cmd.Alert.EXTRA_ALARM);
		if(null == mAlarm) return false;
		mTriggerTime = mAlarm.trigger;
		
		//sign changed by reason
        mAlarm = AlarmDao.getAlarm(getContentResolver(), mAlarm.id);
        mAlarm.trigger = mTriggerTime;
		return true;
	}
	
	protected void requestFullScreen()
	{
		requestWindowFeature(android.view.Window.FEATURE_NO_TITLE);

		final Window win = getWindow();
		win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
				| WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
		// Turn on the screen unless we are being launched from the AlarmAlert
		// subclass.
		if (!getIntent().getBooleanExtra(SCREEN_OFF, false))
		{
			win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
					| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
					| WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON);
		}
	}
	
	private void registerReceiver()
	{		
		mReceiver = new MReceiver();
        IntentFilter filter = new IntentFilter(Cmd.ACTION_ALARM_KILLED);
        filter.addAction(Cmd.ACTION_ALARM_SNOOZE);
        filter.addAction(Cmd.ACTION_ALARM_TIMEOUT);
        registerReceiver(mReceiver, filter);
	}
	
	private void snooze()
	{
		if(AlarmCore.canSnoozed(this, mAlarm.id))
		{

			MobclickAgent.onEvent(this, "alert_op", "snooze-ok");
			final Settings s = Settings.getInstance(this);
			final long d = s.getSnoozeDuration(Settings.SNOOZE_DURATION_DEFAULT);
			mAlarm.trigger += d * 1000L * 60L;
			Calendar c = Calendar.getInstance();
			c.setTimeInMillis(mAlarm.trigger);
			Log.f("snooze", "id = " + mAlarm.id + ", trigger : " + new DateFormat().format("yyyy/MM/dd kk:mm", c) + ",label:" + mAlarm.label);
			AlarmCore.snoozeAlarm(this, mAlarm, false);
			finish();
		}
		else
		{
			Log.f("snooze", "over 5 times, label:" + mAlarm.label);
			UxToast.sshow(this, R.string.alert_tip_timeout);
			MobclickAgent.onEvent(this, "alert_op", "snooze-timeout");
		}
	}
	
	private void dismiss()
	{
		Log.d("new-zzm", "dismiss : " + "dismissAlarm...");
		if(null != mAlarm)
		{
			AlarmCore.dismissAlarm(this, mAlarm.id, false);

			MobclickAgent.onEvent(this, "alert_op", "dismiss");
		}
	}
	
	protected void onAlarmTimeout(Intent intent)
	{	
		Log.d("new-zzm", "alert act : " + "onAlarmTimeout, finish...");
		finish();
	}
	
	protected void onAlarmKilled(Intent intent)
	{	
		Log.d("new-zzm", "alert act : " + "onAlarmKilled, finish...");
		finish();
	}
	
	// Receives the ALARM_KILLED action from the AlarmKlaxon,
	// and also ALARM_SNOOZE_ACTION / ALARM_DISMISS_ACTION from other
	// applications
	private class MReceiver extends BroadcastReceiver
	{
		@Override
		public void onReceive(Context context, Intent intent)
		{
			String action = intent.getAction();
			if (action.equals(Cmd.ACTION_ALARM_TIMEOUT))
			{
				onAlarmTimeout(intent);
			} 
			else if(action.equals(Cmd.ACTION_ALARM_KILLED))
			{
				onAlarmKilled(intent);
			}
		}
	};
}
